package com.dagr.wordboxoid;

import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.dagr.wordboxoid.content.WordCard;
import com.dagr.wordboxoid.content.WordCardDatabase;

public class MainActivity extends Activity implements OnClickListener, OnEditorActionListener {

	private TextView mQuestionView;
	private EditText mAnswerText;

	private WordCard mCurrentWordCard;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		mQuestionView = (TextView) findViewById(R.id.questionView);
		mAnswerText = (EditText) findViewById(R.id.answerText);

		mAnswerText.setOnEditorActionListener(this);
		findViewById(R.id.okButton).setOnClickListener(this);

		mCurrentWordCard = nextWordCard();
		fillViews(mCurrentWordCard);
	}

	private WordCard nextWordCard() {
		List<WordCard> wordCards = WordCardDatabase.findWordCards(getResources().getAssets(), "etape5.txt");
		int randomIndex = new Random().nextInt(wordCards.size());

		return wordCards.get(randomIndex);
	}

	private void fillViews(WordCard wordCard) {
		mQuestionView.setText(wordCard.getSide1());
		mAnswerText.setText(null);
	}

	public void onClick(View view) {
		if (view.getId() == R.id.okButton) {
			onAnswerAction();
		} else {
			throw new IllegalArgumentException("unknown view: " + view);
		}
	}

	public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
		if (view == mAnswerText) {
			if (event.getAction() == KeyEvent.ACTION_UP) {
				onAnswerAction();
			}

			return true;
		} else {
			throw new IllegalArgumentException("unknown view: " + view);
		}
	}

	private void onAnswerAction() {
		String side1 = mCurrentWordCard.getSide1();
		String side2 = mCurrentWordCard.getSide2();
		String answer = mAnswerText.getText().toString();
		if (!side2.equals(answer)) {
			String message = "Deine Antwort '" + answer + "' ist falsch!";
			message += "\n";
			message += "Die richtige Antwort für '" + side1 + "' ist '" + side2 + "'.";

			createResultDialog(message);
		}

		mCurrentWordCard = nextWordCard();
		fillViews(mCurrentWordCard);
	}

	private void createResultDialog(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.result);
		builder.setMessage(message);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setNeutralButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int i) {
				dialog.dismiss();
			}
		});

		AlertDialog dialog = null;
		dialog = builder.create();
		dialog.show();
	}

}